package com.gitee.feizns.web.ex.impl;

import com.gitee.feizns.web.domain.result.Ret;
import com.gitee.feizns.web.ex.CustomizeExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;

/**
 * @author feizns
 * @since 2019/7/7
 */
public class BindExceptionHandler implements CustomizeExceptionHandler<BindException, Object> {

    @Override
    public ResponseEntity<Ret<Object>> handle(BindException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Ret.err(HttpStatus.BAD_REQUEST.value(), getDefaultMessage(e)));
    }

    private String getDefaultMessage(BindException e) {
        FieldError error = e.getBindingResult().getFieldError();
        return  String.format("Parameter %s %s.", error.getField(), error.getDefaultMessage());
    }

}
